package webview

import (
	"gitee.com/snxamdf/wui/logs"
	"gitee.com/snxamdf/wui/util/w"
	"sync"
)

var componentLock sync.RWMutex

type Data interface{}

var componentListen = map[string]ComponentInterface{}

type Component struct {
	name    string
	widgets map[string]WidgetInterface
	wv      WV
}

//创建一个组件
func NewComponent(componentName string, wv WV) ComponentInterface {
	if componentName == "" {
		logs.Info("创建新的组件名字不能为空")
		return nil
	}
	if c, ok := componentListen[componentName]; ok {
		return c
	}
	c := &Component{
		name:    componentName,
		widgets: make(map[string]WidgetInterface),
		wv:      wv,
	}
	componentListen[componentName] = c
	return c
}

//获取组件名称
func (m *Component) GetName() string {
	return m.name
}

//创建一个小控件
func (m *Component) NewWidget(widgetId string) WidgetInterface {
	if w, ok := m.widgets[widgetId]; ok {
		return w
	}
	widget := &Widget{
		id:        widgetId,
		component: m,
		value:     *w.NewMap(),
	}
	m.widgets[widgetId] = widget
	return widget
}

//获取一个小控件
func (m *Component) GetWidget(widgetId string) WidgetInterface {
	return m.widgets[widgetId]
}

func (m *Component) GetWidgets() map[string]WidgetInterface {
	return m.widgets
}

//设置一个小控件，返回老的控件信息
func (m *Component) SetWidget(widgetId string, w WidgetInterface) WidgetInterface {
	old := m.widgets[widgetId]
	m.widgets[widgetId] = w
	return old
}

func (m *Component) GetWV() WV {
	return m.wv
}
